package cn.xk.basic.interceptor;

import cn.xk.jwt.JwtUtils;
import cn.xk.jwt.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor { // /**
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token"); //f0716115-0a19-4d21-8fb5-7eec8571011d
        if (token != null) {
            try {
                //解密之后获取登录信息
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader()
                        .getResource("auth_rsa.pub").getFile());
                JwtUtils.getInfoFromToken(token, publicKey);
                return true;//没有刷新过期时间
            } catch (Exception e) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false; //不会走controller

            }
        }

        //最终目的是要调转到登录页面：响应json数据给前端，让前端判断去跳转
        //告诉浏览器，我响应了一个json数据给你，编码是u8 - 浏览器接收之后会自动转换成json对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false; //不会走controller了
    }

}



